// src/stores/cartStore.js
import { defineStore } from 'pinia';
import { getCartList, addItemToCart, updateItemQuantity, deleteItem } from '@/api/CartApi';
import { ElMessage } from 'element-plus';

export const useCartStore = defineStore('cart', {
    state: () => ({
        items: [], // 存储购物车商品列表
        count: 0,  // 购物车商品总数量（或总品类数量）
        totalAmount: 0, // 购物车商品总金额
        loading: false, // 添加一个加载状态，用于 UI 交互
    }),
    actions: {
        /**
         * 设置购物车商品列表并重新计算总数和总金额
         * @param {Array<Object>} cartItems - 从后端获取的购物车商品列表
         */
        setCartItems(cartItems) {
            if (cartItems != null && cartItems.length > 0) {
                // 关键修改：为每个商品项添加 checked 状态，并默认为 false
                this.items = cartItems.map(item => ({ ...item, checked: false }));
                this.count = cartItems.reduce((sum, item) => sum + item.quantity, 0);
                this.totalAmount = cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
            } else {
                this.items = [];
                this.count = 0;
                this.totalAmount = 0;
            }
        },

        /**
         * 从后端获取最新购物车数据并更新 Store
         */
        async fetchCartItems() {
            this.loading = true;
            try {
                const response = await getCartList();
                if (response.data.code === 1) {
                    this.setCartItems(response.data.data);
                } else {
                    console.error('Failed to fetch cart items:', response.data.msg);
                    this.setCartItems([]);
                    ElMessage.error('获取购物车失败：' + response.data.msg);
                }
            } catch (error) {
                console.error('Error fetching cart items:', error);
                this.setCartItems([]);
            } finally {
                this.loading = false;
            }
        },

        // 其他 actions (addItem, updateItemQuantity, removeItem) 保持不变
        async addItem(productData) {
            this.loading = true;
            try {
                await addItemToCart(productData);
                await this.fetchCartItems();
            } catch (error) {
                console.error('Error adding item to cart:', error);
            } finally {
                this.loading = false;
            }
        },

        async updateItemQuantity(cartId, newQuantity) {
            this.loading = true;
            try {
                const itemToUpdate = this.items.find(item => item.cartId === cartId);
                if (itemToUpdate) {
                    await updateItemQuantity({ cartId, quantity: newQuantity });
                    ElMessage.success('商品数量更新成功');
                    await this.fetchCartItems();
                }
            } catch (error) {
                console.error('Error updating item quantity:', error);
                await this.fetchCartItems();
            } finally {
                this.loading = false;
            }
        },

        async removeItem(cartId) {
            this.loading = true;
            try {
                const response = await deleteItem(cartId);
                if (response.data.code === 1) {
                    ElMessage.success('商品已成功移除购物车');
                    await this.fetchCartItems();
                } else {
                    ElMessage.error(response.data.msg || '移除商品失败');
                }
            } catch (error) {
                console.error('Error removing item from cart:', error);
            } finally {
                this.loading = false;
            }
        },

        /**
         * 切换单个商品的选中状态
         * @param {string} cartId - 要切换选中状态的商品ID
         */
        toggleItemChecked(cartId) {
            const item = this.items.find(i => i.cartId === cartId);
            if (item) {
                item.checked = !item.checked;
            }
        },

        /**
         * 切换所有商品的选中状态（全选/全不选）
         * @param {boolean} checked - 目标选中状态
         */
        toggleAllItemsChecked(checked) {
            this.items.forEach(item => {
                item.checked = checked;
            });
        },
    },
    getters: {
        cartTotalCount: (state) => state.count,

        // 计算选中商品的总数量
        checkedItemCount: (state) => state.items.filter(item => item.checked).length,

        // 计算选中商品的总价格
        checkedTotalPrice: (state) => state.items.filter(item => item.checked).reduce((sum, item) => sum + item.price * item.quantity, 0),

        // 判断是否所有商品都已选中
        isAllItemsChecked: (state) => state.items.length > 0 && state.items.every(item => item.checked),
    }
});